# 数据库连接依赖注入
from tortoise.transactions import in_transaction

async def get_db():
    async with in_transaction() as connection:
        yield connection
        
"""  
优点：
● • 保证事务一致性
● • 避免重复创建连接
● • 易于测试（可替换 get_db）
# api/user.py
from fastapi import APIRouter, Depends
from database import get_db

router = APIRouter()

@router.get("/users")
async def get_users(db=Depends(get_db)):
    return await db.execute_query_dict("SELECT * FROM user")

"""

# 权限验证依赖注入
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from models import User  # 假设你有一个 User 模型

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")

def decode_token(token: str):
    # 实际项目中请用 JWT 解码
    if token == "admin-token":
        return {"id": 1, "is_admin": True}
    elif token == "user-token":
        return {"id": 2, "is_admin": False}
    return None

async def verify_token(token: str = Depends(oauth2_scheme)) -> int:
    user = decode_token(token)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid token")
    return user["id"]

async def admin_required(user_id: int = Depends(verify_token)):
    user = await User.get(id=user_id)
    if not user.is_admin:
        raise HTTPException(status_code=403, detail="Admin only")
    return user

""" 
@app.get("/admin")
async def admin_dashboard(current_user=Depends(admin_required)):
    return {"msg": f"Welcome admin {current_user.username}"}
"""
# 请求上下文注入（IP、UA、Headers）
from fastapi import Request

async def get_request_context(request: Request):
    return {
        "ip": request.client.host,
        "user_agent": request.headers.get("user-agent"),
        "headers": dict(request.headers)
    }
""" 
@app.get("/log")
async def log(ctx = Depends(get_request_context)):
    print(f"来自 {ctx['ip']} 的请求，UA: {ctx['user_agent']}")
    return {"message": "Logged"}

优点：
● • 自动提取请求相关数据
● • 避免在每个接口中手动处理
● • 支持结构化日志、追踪、限流等高级特性
"""
# 单元测试更方便（mock 依赖）
from fastapi.testclient import TestClient
from main import app
# from database import get_db

# Mock 数据库连接
async def override_get_db():
    class DummyDB:
        async def execute_query_dict(self, sql):
            return [{"id": 1, "username": "test_user"}]
    yield DummyDB()

app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)

def test_get_users():
    response = client.get("/users")
    assert response.status_code == 200
    assert response.json() == [{"id": 1, "username": "test_user"}]
    
""" 
你也可以 override 权限验证、上下文获取等依赖项：

from auth import verify_token

# mock 权限校验返回用户 id
app.dependency_overrides[verify_token] = lambda: 1
🎯 优点：
● • ⚡ 测试更快，不依赖数据库
● • 🧪 可控输入输出，断言更精准
● • 🧹 没有副作用，测试隔离性强
"""